/*
 * @Author: 聆风
 * @Date: 2025-08-23 17:21:03
 * @LastEditors: 聆风 522361856@qq.com
 * @LastEditTime: 2025-08-24 15:16:14
 * @FilePath: \​monoFE​​\scripts\rollup.config.mjs
 *
 * Copyright (c) 2025 by 聆风, All Rights Reserved.
 */
import path from "path"; // 添加path模块导入
import {
  getPackages,
  readPackageJson,
  packagesDir,
  readTsconfigJson,
} from "./utils.js";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import { dts } from "rollup-plugin-dts";
import typescript from "@rollup/plugin-typescript";
import terser from "@rollup/plugin-terser";

// 为每个包创建配置
export function createPackageConfig(pkg) {
  const packageJson = readPackageJson(pkg);
  const buildOptions = packageJson.buildOptions || {};
  const pkgName = packageJson.name || pkg;
  const input = path.join(packagesDir, pkg, "index.ts");
  const outputDir = path.join(packagesDir, pkg, "dist");

  const formats = buildOptions.formats || ["esm-bundler", "cjs"];
  const globalName =
    buildOptions.name ||
    pkgName.replace(/@.*\//, "").replace(/-/g, "_").toUpperCase();

  let tsconfig = readTsconfigJson();
  tsconfig.compilerOptions.outDir = outputDir;
  // 主构建配置
  const mainConfig = {
    input,
    output: [],
    plugins: [nodeResolve(), commonjs(), typescript(tsconfig), terser()],
    external: [
      ...Object.keys(packageJson.dependencies || {}),
      ...Object.keys(packageJson.peerDependencies || {}),
    ],
  };

  // 根据格式添加输出配置
  formats.forEach((format) => {
    switch (format) {
      case "esm-bundler":
        mainConfig.output.push({
          file: path.join(outputDir, `${pkg}.esm-bundler.js`),
          format: "es",
          sourcemap: true,
        });

        break;
      case "cjs":
        mainConfig.output.push({
          file: path.join(outputDir, `${pkg}.cjs.js`),
          format: "cjs",
          sourcemap: true,
        });
        break;
      case "iife":
      case "global":
        mainConfig.output.push({
          file: path.join(outputDir, `${pkg}.global.js`),
          format: "iife",
          name: globalName,
          sourcemap: true,
        });
        break;
      case "umd":
        mainConfig.output.push({
          file: path.join(outputDir, `${pkg}.umd.js`),
          format: "umd",
          name: globalName,
          sourcemap: true,
        });
        break;
    }
  });

  // 类型声明配置
  const dtsConfig = {
    input,
    output: {
      file: path.join(outputDir, "index.d.ts"),
      format: "es",
    },
    plugins: [dts()],
  };

  return [mainConfig, dtsConfig];
}

/**
 * 获取所有包的配置
 */
export function getAllConfigs() {
  return getPackages()
    .map((pkg) => createPackageConfig(pkg))
    .flat();
}
